package com.zzyl.service.impl;

import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.LoginVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class MemberServiceImpl implements MemberService {
    private static final String DEFAULT_NAME="用户";
    private final MemberMapper memberMapper;
    private final WeChatService weChatService;
    private final JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1.通过前端传递的code发起远程调用,获取用户的openid
        String openId = weChatService.getOpenId(userLoginRequestDto.getCode());
        //2.通过openid查询数据库,查询用户
        Member member = memberMapper.getByOpenId(openId);
        //3.用户为空的话,构建用户数据(openid)
        if (ObjectUtil.isEmpty(openId)){
            member=Member.builder()
                    .openId(openId)
                    .build();
        }
        //4.根据detail.code查询手机号(微信官方查询)
        String phone = weChatService.getPhone(userLoginRequestDto.getPhoneCode());
        //5.新增或修改用户
        saveOrUpdate(member,phone);
        //6.生成token返回(包含用户的id和名称)
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID,member.getId());
        claims.put(Constants.JWT_USERNAME,member.getName());
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());
        return loginVo;
    }

    private void saveOrUpdate(Member member, String phone) {
        if (ObjectUtil.isEmpty(member.getId())){
            String nickName=DEFAULT_NAME+StringUtils.substring(phone,7);
            member.setName(nickName);
            memberMapper.save(member);
            return;
        }
        if (StringUtils.isNotEmpty(phone)){
            member.setPhone(phone);
            memberMapper.update(member);
        }
    }
}
